﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BoYuanCore.CodeGenerator.code;
using BoYuanCore.CoreCodeTemplates;
using BoYuanCore.CoreCodeTemplates.FreeSql;
using FineUIPro;
using FreeSql.DatabaseModel;
using DbColumnInfo = BoYuanCore.CoreCodeTemplates.DbColumnInfo;

namespace BoYuanCore.CodeGenerator.FreeSqlClass
{
    public partial class SetCode : CodeBasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                txb_Expression.Text = "{0}=p.{0}," + Environment.NewLine;
            }
        }

        protected void Button_save_OnClick(object sender, EventArgs e)
        {
            var tableList=  hd_tables.Text.Split(',');

            if (!Directory.Exists(txb_path.Text))
            {
                Directory.CreateDirectory(txb_path.Text); //建立文件夹
            }

            try
            {
                string parentClass = cb_EntityType.Checked ? "SnowflakEntity" : string.Empty;//是否为雪花实体

                List<DbColumnInfo> cm;
                TableModel table;
                string templateInfo;
                foreach (string tableName in tableList)
                {
                    cm = GetColumnDataByTableName(tableName);//字段信息集合
                    table = new TableModel();
                    table.Columns = cm;
                    table.NamespaceStr = txb_nameSpace.Text.Trim();
                    table.TableName = tableName;
                    table.DbClass = Session["dbtype"].ToString();

                    templateInfo = EntityTemplate.GetCode(table, parentClass);
                   
                    System.IO.File.WriteAllText(txb_path.Text + "\\" + table.TableNameToClassName + ".cs", templateInfo, Encoding.UTF8);
                }

                NotifyInformation("生成代码成功");
            }
            catch (Exception ex)
            {
                NotifyError("生成代码有问题：" + ex.Message);
            }
        }

        /// <summary>
        /// 获取字段信息集合，根据表
        /// </summary>
        /// <param name="tableName">表名称</param>
        /// <returns></returns>
        public List<DbColumnInfo> GetColumnDataByTableName(string tableName)
        {
            DbTableInfo table;
            using (var DB = MyInstance())
            {
                table = DB.DbFirst.GetTablesByDatabase().FirstOrDefault(p => p.Name == tableName);
            }

            var list = table?.Columns.Select(p => new DbColumnInfo()
            {
                TableName = p.Table.Name,
                DbColumnName = p.Name,
                CsType = p.CsType,
                IsIdentity = p.IsIdentity,
                IsNullable = p.IsNullable,
                MaxLength = p.MaxLength,
                Coment = p.Coment,
                DefaultValue = p.DefaultValue,
                IsPrimaryKey = p.IsPrimary,
                DbTypeText = p.DbTypeText,
                DbTypeTextFull = p.DbTypeTextFull
            }).ToList();

            return list;
        }

        protected void Btn_SetSimpleCode_OnClick(object sender, EventArgs e)
        {
            //验证
            string pattern = @"\{\d\}"; //包含{0} {1} 等

            if (Regex.Matches(txb_Expression.Text, pattern).Count == 0)
            {
                Alert.Show("表达式必须含有'{0}'等表达式等!");
                return;
            }

            //显示单表FineuiPro代码
            var tables = hd_tables.Text.Split(',');
            if (hd_tables.Text.Length == 0 || tables.Length == 0)
            {
                NotifyError("获取表集合失败！");
                return;
            }

            try
            {
                string table = tables[0];
                List<FreeSql.DatabaseModel.DbColumnInfo> list;
                using (var DB = MyInstance())
                {
                    list = DB.DbFirst.GetTablesByDatabase().FirstOrDefault(p => p.Name == table)?.Columns;
                }
                StringBuilder sb = new StringBuilder();
                foreach (var colum in list)
                {
                    sb.AppendFormat(txb_Expression.Text
                        , colum.Name
                        , colum.Coment
                        , colum.DbTypeText
                        , colum.DefaultValue
                        , colum.IsPrimary
                        , colum.IsIdentity
                        , colum.IsNullable
                        , colum.MaxLength
                    );

                }

                lb_Select.Text = ShowHighlightCode(sb.ToString());
            }
            catch (Exception exception)
            {
                NotifyError(exception.Message);
                return;
            }

            PageContext.RegisterStartupScript("ShowHighlight();");
        }

    }
}
